import cache from "./cache";
import { apiLogin } from "@/apis/login";
import { router } from "./tools";
import { useUserStore } from "@/stores/user";
import userService from "@/services/userService";
import { apiGetUserInfo } from "@/apis/user";

export const setToken = (token: string = "") => {
  cache.set("token", token);
};
export const getToken = (): string => {
  const userStore = useUserStore();
  return cache.get("token") || userStore?.userInfo?.token || null;
};
// 清楚token
export const removeToken = (): void => {
  cache.remove("token");
};
// #ifdef MP-WEIXIN
// 微信小程序登录
export const wxLogin = () => {
  return new Promise((resole, reject) => {
    uni.login({
      provider: "weixin",
      onlyAuthorize: true, // 微信登录仅请求授权认证
      success: function (event: IWxLogin) {
        // const { code } = event;
        resole(event);
      },
      fail: function (err) {
        // 登录授权失败
        // err.code是错误码
        reject(err);
      },
    });
  });
};
// 微信静默登录
export const login = async () => {
  setTimeout(async() => {

    const userStore = useUserStore();
    // if (userStore.state.isLogin) {
    //   return false;
    // }
    // uni.showLoading({ title: '正在重新登陆！', mask: true });
    const inviterId = uni.getStorageSync("inviterId") ? uni.getStorageSync("inviterId") : '';
    let commodityId = uni.getStorageSync("shareDetailId") ? uni.getStorageSync("shareDetailId") : '';
    let shareTitle = uni.getStorageSync("shareTitle")
    if (shareTitle !== '推荐榜') {
      commodityId = ''
    }
    console.log('shareTitle----', shareTitle)

    console.log('commodityId---', commodityId)
    let wxRes = await wxLogin();
    let res = await apiLogin({ code: wxRes.code, inviterId, commodityId });
    if (res.code === 500 && res.msg === "用户未授权") {
      // return false;
      cache.remove("token");
      // router('/pages/login/login');
      return false;
    }
    // setToken(res.data.appUser.token);
    // 保存用户信息
    // userService.save();
    // 登录
    userStore.login(res.data.appUser);
    // const userinfo = await apiGetUserInfo();
    // userStore.setUserInfo(userinfo);

    // uni.hideLoading();
  }, 500);

};
// #endif

// #ifdef H5

// #endif
